# -*- coding: utf-8 -*-
import string
from string import Template
import os, sys, re, traceback
from datetime import datetime
from string import Template
import json


# template = "hello %s , your website is %s " % ("简书", "http://www.jianshu.com/")
# print(template)
#
# template = "hello {0} , your website is {1} ".format("简书", "http://www.jianshu.com/")
# print(template)
#
# tempTemplate = string.Template("Hello $name ,your website is $message")
# print(tempTemplate.substitute(name='大CC', message='http://blog.me115.com'))


def camel_to_underline(camel_format):
    """
        驼峰命名格式转下划线命名格式
    """
    underline_format = ''
    if isinstance(camel_format, str):
        for _s_ in camel_format:
            underline_format += _s_ if _s_.islower() else '_' + _s_.lower()
    return underline_format


def generateAndroidJavaCode(app_id, package_name, template, fileName, key_word):
    className = os.path.splitext(fileName)[0]
    full_pkg = app_id + "." + package_name
    path = "./" + full_pkg.replace('.', '/')
    filePath = r'%s/%s' % (path, fileName)
    if os.path.exists(path) == False:
        os.makedirs(path)
    class_file = open(filePath, 'w')
    lines = []
    # 模版文件
    template_file = open(r"./code_gen/" + template, 'r')
    tmpl = Template(template_file.read())
    # 模版替换
    lines.append(tmpl.substitute(
        KEY_WORD=key_word,
        PACKAGE_NAME=package_name,
        ANDROID_APP_ID=app_id,
        DATA=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        CLASS_NAME=className,
        PKG_NAME=package_name,  # NearAct -> near
        XML_NAME=camel_to_underline(key_word)
    ))
    # 0.将生成的代码写入文件
    class_file.writelines(lines)
    class_file.close()
    print 'generate %s over. ~ ~' % filePath


def gen(app_id1, pkg_name1, key_word1):
    full_pkg = app_id1 + "." + pkg_name1
    #
    # gen_act(full_pkg)
    gen_frgm_presenter("Presenter", full_pkg, key_word1)
    gen_list_frgm("Frgm", full_pkg, key_word1)
    gen_list_xml("frgm", full_pkg, key_word1)


def gen_list_frgm(prefix, full_pkg, key_word1):
    # 模版文件
    class_name = key_word1 + prefix
    file_name = class_name + ".java"
    gen2(template_name="BaseListFragment.java.tpl",
         package_name1=full_pkg,
         file_name2=file_name,
         KEY_WORD=key_word,
         PACKAGE_NAME=full_pkg,
         ANDROID_APP_ID=app_id,
         DATA=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
         CLASS_NAME=class_name,
         XML_NAME="frgm" + camel_to_underline(key_word))
    pass


def gen_act():
    # 模版文件
    template_file = open(r"./code_gen/BaseListActivity.java.tpl", 'r')
    lines = []
    pass


def gen_frgm_presenter(prefix, package_name1, key_word1):
    # 模版文件
    class_name = key_word1 + prefix
    file_name = class_name + ".java"
    gen2(template_name="BaseListPresenter.java.tpl",
         package_name1=package_name1,
         file_name2=file_name,
         KEY_WORD=key_word,
         PACKAGE_NAME=package_name1,
         ANDROID_APP_ID=app_id,
         CLASS_NAME=class_name,
         DATA=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
         )
    pass


def gen_adapter():
    # 模版文件
    template_file = open(r"./code_gen/BaseAdapter.java.tpl", 'r')

    pass


def gen_list_xml(prefix, package_name1, key_word1):
    # 模版文件
    file_name = prefix + camel_to_underline(key_word1) + ".xml"
    gen2(template_name="list.xml.tpl",
         package_name1=package_name1,
         file_name2=file_name)
    pass


def gen2(template_name, package_name1, file_name2, **kws):
    # 替换模板文件
    template_file = open(r"./code_gen/" + template_name, 'r')
    tmpl = Template(template_file.read())
    result = tmpl.substitute(kws)
    lines = []
    lines.append(result)

    # 0.将生成的代码写入文件 (包名和文件名 省去创建文件夹的麻烦)
    path = "./" + package_name1.replace('.', '/')
    file_path = r'%s/%s' % (path, file_name2)
    if os.path.exists(path) == False:
        os.makedirs(path)
    class_file = open(file_path, 'w')
    class_file.writelines(lines)
    class_file.close()


# 1. 解析配置文件

# 列表的Fragment的代码生成器 (写个界面配置 路径 参数 JSON 最好可以拖拽)
# For My Favorite Lady
configuration = """
{
  "app_id":"com.woai.vichat",
  "list":[
      {
          "key_word":"MessageList",
          "package_name":"message",
          "template":"list.xml.tpl",
          "fileList":[
              "frgm_message_list.xml"
          ]
      },{
          "key_word":"MessageList",
          "package_name":"message",
          "template":"BaseListFragment.java.tpl",
          "fileList":[
              "MessageListFrgm.java"
          ]
      },{
          "key_word":"MessageList",
          "package_name":"message",
          "template":"BaseListPresenter.java.tpl",
          "fileList":[
              "MessageListPresenter.java"
          ]
      }
  ]
}
"""
# configurationJson = json.loads(configuration)
# # 2. 按照模板生成对应的文件
# app_id = configurationJson["app_id"]
# for filesInfo in configurationJson["list"]:
#     package_name = filesInfo["package_name"]
#     key_word = filesInfo["key_word"]
#     template = filesInfo["template"]
#     for fileName in filesInfo["fileList"]:
#         generateAndroidJavaCode(app_id, package_name, template, fileName, key_word)

app_id = "com.woai.vichat"
pkg_name = "video"
key_word = "VideoList"
gen(app_id, pkg_name, key_word)
